package com.nuc.thread.cas;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 诗酒趁年华
 * @version 1.0.0
 * @Description 不加锁
 * @createTime 2021年07月11日 18:15:00
 */
public class AccountCas implements Account{
    private AtomicInteger balance;

    public AccountCas(Integer balance) {
        this.balance = new AtomicInteger(balance);
    }

    @Override
    public Integer getBalance() {
        return balance.get();
    }

    @Override
    public void withDraw(Integer amount) {
        while (true){
            //修改之前
            int prev = balance.get();
            //要修改的余额
            int next = prev - amount;

            //真正修改
            if (balance.compareAndSet(prev,next)){
                break;
            }
        }
    }
}
